package sk.tramtatiri.data.dao.jpa;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceException;
import javax.persistence.TypedQuery;

import org.springframework.orm.jpa.JpaCallback;
import org.springframework.transaction.annotation.Transactional;

import sk.tramtatiri.data.dao.interfaces.SportDao;
import sk.tramtatiri.data.dataobjects.Sport;

public class SportDaoJPAImp extends AbstractDaoJPAImpl<Sport> implements SportDao {

	public SportDaoJPAImp() {
		super(Sport.class);
	}

	@Transactional
	public List<Sport> findAll() {
		return getJpaTemplate().execute(new JpaCallback<List<Sport>>() {
			public List<Sport> doInJpa(EntityManager em) throws PersistenceException {
				TypedQuery<Sport> query = em.createQuery("select s from Sport s order by s.category", Sport.class);
				return query.getResultList();
			}
		});
	}

	@Transactional
	public int countAll() {
		// TODO Auto-generated method stub
		return 0;
	}

	@Transactional
	public Sport findName(final String name) {
		try{
			return getJpaTemplate().execute(new JpaCallback<Sport>() {
				public Sport doInJpa(EntityManager em) throws PersistenceException {
					TypedQuery<Sport> query = em.createQuery("select r from Sport r where name='"+name+"'", Sport.class);
					return query.getSingleResult();
				}
			});
		}catch (Exception e) {
			return null;
		}
	}

	@Transactional
	public void delete(Sport o) {
		Sport s = getJpaTemplate().find(Sport.class, o.getId());
		getJpaTemplate().remove(s);
	}

}
